package com.zyf.service.service;


import com.zyf.service.config.StorageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class StorageService {
    private final Path rootLocation;

    @Autowired
    public StorageService(StorageProperties properties) {
        this.rootLocation = Paths.get(properties.getLocation());
    }


    public void init() {
        try {
            Files.createDirectories(rootLocation);
        }
        catch (IOException e) {
            throw new BusException("Could not initialize storage");
        }
    }

    /**
     * @Author: kech
     * @Description: 存入
     * @Date: 2021/12/31
     */
    public String store(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                throw new BusException("Failed to store empty file.");
            }
            //子文件夹用uuid命名
            String uuidName = UUID.randomUUID().toString();
            File dir = new File(rootLocation.toString()+"/"+uuidName);
            dir.mkdir();
            Path destinationFile = this.rootLocation.resolve(dir.getAbsolutePath()+"/"+file.getOriginalFilename())
                    .normalize().toAbsolutePath();
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, destinationFile,
                        StandardCopyOption.REPLACE_EXISTING);
                return uuidName+"/"+file.getOriginalFilename();
            }
        }
        catch (IOException e) {
            throw new BusException("Failed to store file.");
        }
    }

    /**
     * @Author: kech
     * @Description:遍历本地文件夹
     * @Date: 2021/12/31
     */
    public List<String> loadAll() {
        try {
            List<String> res = new ArrayList<>();
            File file = new File("./"+this.rootLocation.getFileName());
            if(null != file && file.isDirectory()){
                File[] fs=file.listFiles();
                for(File f: fs){
                    if(!f.isDirectory())
                        res.add(f.getName());
                }
            }
            return res;
        }
        catch (Exception e) {
            throw new BusException("Failed to read stored files");
        }
    }

    public Path load(String filename) {
        return rootLocation.resolve(filename);
    }

    public Resource loadAsResource(String filename) {
        try {
            Path file = load(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            }
            else {
                throw new BusException(
                        "Could not read file: " + filename);
            }
        }
        catch (MalformedURLException e) {
            throw new BusException("Could not read file: " + filename);
        }
    }

    public void deleteAll() {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }
}
